package com.example.blackmarket.module.Me.Recharge;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.blackmarket.R;
import com.example.blackmarket.entities.FailureResponse;
import com.example.blackmarket.module.Base.BaseActivity;
import com.example.blackmarket.module.Me.MeFragment;

import java.util.Map;

public class AlipayActivity extends BaseActivity implements AlipayView{

    private AliPayPresenter aliPayPresenter;

    private EditText editText;
    private Button recharge;
    final int SDK_PAY_FLAG = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        super.init();
        aliPayPresenter = new AliPayPresenter(this);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        new Handler().postDelayed(() -> {
                            Intent intent = new Intent();
                            intent.putExtra("null", "not thing");
                            setResult(RESULT_OK, intent);
                            finish();
                        }, Toast.LENGTH_SHORT);
//                        finish();
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**
     * 支付宝支付业务示例
     */
//    public void payV2(View v) {
////        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
////            showAlert(this, getString(R.string.error_missing_appid_rsa_private));
////            return;
////        }
//
//        /*
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
//         *
//         * orderInfo 的获取必须来自服务端；
//         */
////        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
////        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
////        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
////
////        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
////        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        String orderInfo = "";
//
//        final Runnable payRunnable = new Runnable() {
//
//            @Override
//            public void run() {
//                PayTask alipay = new PayTask(AlipayActivity.this);
//                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Log.i("msp", result.toString());
//
//                Message msg = new Message();
//                msg.what = SDK_PAY_FLAG;
//                msg.obj = result;
//                mHandler.sendMessage(msg);
//            }
//        };
//
//        // 必须异步调用
//        Thread payThread = new Thread(payRunnable);
//        payThread.start();
//    }

    @Override
    protected void onBindView() {
        editText = findViewById(R.id.moneyText);
        recharge = findViewById(R.id.aliPayButton);
    }

    @Override
    protected void setButtonClick() {
        recharge.setOnClickListener(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.pay_main;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.aliPayButton:
                float money = Float.parseFloat(editText.getText().toString());
                aliPayPresenter.recharge(money);
//                final Runnable payRunnable = new Runnable() {
//
//                    @Override
//                    public void run() {
//                        PayTask alipay = new PayTask(AlipayActivity.this);
//                        Map<String, String> result = alipay.payV2(orderInfo, true);
//                        Log.i("msp", result.toString());
//
//                        Message msg = new Message();
//                        msg.what = SDK_PAY_FLAG;
//                        msg.obj = result;
//                        mHandler.sendMessage(msg);
//                    }
//                };
//
//                // 必须异步调用
//                Thread payThread = new Thread(payRunnable);
//                payThread.start();
                break;
        }
    }

    @Override
    public void showSuccess(String tradeInfo) {
        final Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(AlipayActivity.this);
            Map<String, String> result = alipay.payV2(tradeInfo, true);
            Log.i("msp", result.toString());

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void showFailure(FailureResponse failureResponse) {

    }
}
